<template>
  <el-row class="p-5 pt-0" @keyup.enter="getData">

    <el-col v-if="showSearch">
      <el-form ref="searchForm" :inline="true" :model="search" class="demo-form-inline">
        <el-form-item label="部门名称" class="font-black">
          <el-input v-model="search.deptName" :disabled="loading" :size="store.layoutSize" clearable
                    placeholder="请输入部门名称"/>
        </el-form-item>
        <el-form-item label="状态" class="font-black">
          <el-select v-model="search.status" :disabled="loading" :size="store.layoutSize" clearable
                     placeholder="部门状态" @change="getData">
            <el-option v-for="item in statusData.data" :label="item.dictLabel" :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space
                     type="primary"
                     @click="getData">
            <template #icon>
              <el-icon>
                <Search/>
              </el-icon>
            </template>
            查询
          </el-button>
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space plain
                     @click="resetForm">
            <template #icon>
              <el-icon>
                <Refresh/>
              </el-icon>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-col class="flex justify-between">
      <div>
        <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space plain
                   type="primary"
                   @click="add">
          <template #icon>
            <el-icon>
              <Plus/>
            </el-icon>
          </template>
          新增
        </el-button>
        <el-button :disabled="loading" :size="store.layoutSize" auto-insert-space plain type="info" @click="expand">
          <template #icon>
            <el-icon>
              <Sort/>
            </el-icon>
          </template>
          展开/折叠
        </el-button>
      </div>
      <div>
        <el-tooltip
            class="box-item"
            effect="dark"
            :content="showSearch?'隐藏搜索':'显示搜索'"
            placement="top"
        >
          <el-button :color="store.getTheme" :size="store.layoutSize" @click="showSearch = !showSearch" circle>
            <template #icon>
              <el-icon>
                <Search/>
              </el-icon>
            </template>
          </el-button>
        </el-tooltip>
        <el-tooltip
            class="box-item"
            effect="dark"
            content="刷新"
            placement="top"
        >
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" circle @click="getData">
            <template #icon>
              <el-icon>
                <Refresh/>
              </el-icon>
            </template>
          </el-button>
        </el-tooltip>
      </div>
    </el-col>

    <el-col class="mt-2">
      <el-table v-if="refreshTable" :size="store.layoutSize" v-loading="loading"
                element-loading-text="正在努力加载中..."
                :data="tableData.data" ref="tableRef"
                style="width: 100%" table-layout="auto" row-key="deptId" :default-expand-all="expandAll"
                highlight-current-row empty-text="无数据" :tree-props="{children: 'children'}">

        <el-table-column label="部门名称" width="180" prop="deptName"/>

        <el-table-column align="center" label="排序" prop="orderNum" width="200"/>

        <el-table-column align="center" label="状态" width="150">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">{{
                scope.row.status === '0' ? '正常' : '停用'
              }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建时间" width="180">
          <template #default="scope">
            {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-link type="primary" :underline="false" class="text-xs" :style="{color: store.getTheme}"
                     :size="store.layoutSize"
                     @click="update(scope.row)">
              <el-icon>
                <EditPen/>
              </el-icon>
              修改
            </el-link>
            <el-link type="primary" :underline="false" class="text-xs ml-3" :style="{color: store.getTheme}"
                     :size="store.layoutSize" @click="addChild(scope.row)">
              <el-icon>
                <Plus/>
              </el-icon>
              新增
            </el-link>
            <el-link type="primary" :underline="false" class="text-xs ml-3" :style="{color: store.getTheme}"
                     :size="store.layoutSize" v-if="scope.row.parentId !== 0"
                     @click="del(scope.row)">
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </el-link>
          </template>
        </el-table-column>

      </el-table>
    </el-col>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="submitForm" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <el-tree-select
                  v-model="form.parentId"
                  :data="tableData.data"
                  node-key="deptId"
                  :props="{label:'deptName'}"
                  highlight-current
                  check-strictly
                  :render-after-expand="false" placeholder="选择上级部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="radio">
                <el-radio v-for="item in statusData.data" :key="item.dictCode"
                          :label="item.dictValue">{{
                    item.dictLabel
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="flex justify-end">
        <el-button :color="store.getTheme" :loading="btnLoading" auto-insert-space type="primary"
                   @click="submit(submitForm)">确定
        </el-button>
        <el-button auto-insert-space @click="open = false">取消</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>

<script setup lang="ts">
import {useStore} from "@/store";
import {nextTick, reactive, ref} from "vue";
import {delDeptData, getDeptData, saveDeptData} from "@/api/dept";
import moment from "moment";
import {getDictData} from "@/api/dictData";
import {ElMessageBox, ElNotification, FormInstance, FormRules} from "element-plus";
//引入store
const store = useStore()
const searchForm = ref<FormInstance>()
const submitForm = ref<FormInstance>()

const tableRef = ref()

const refreshTable = ref(true)

//展开树状图
const expandAll = ref(true)

function expand() {
  refreshTable.value = false
  expandAll.value = !expandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

//弹出层标题
const title = ref("")

//是否显示弹出层
const open = ref(false)

//显示搜索框
const showSearch = ref(true)

//表格加载
const loading = ref(false)

//部门状态按钮
const radio = ref('0')

//赋值状态信息
const statusData = reactive({
  data: []
})
getDictData({'dictType': 'sys_normal_disable'}).then(result => {
  statusData.data = result.data.data
})

//新增、修改表单
const form = reactive({
  deptId: null,
  parentId: null,
  deptName: null,
  orderNum: null,
  leader: null,
  phone: null,
  email: null,
  status: null,
  createBy: null,
  updateBy: null,
})

//清空表单
function clearForm() {
  form.deptId = null
  form.parentId = null
  form.deptName = null
  form.orderNum = null
  form.leader = null
  form.phone = null
  form.email = null
  form.status = null
  form.createBy = null
  form.updateBy = null
}

//新增按钮
function add() {
  clearForm()
  title.value = '添加部门'
  open.value = true
}

//新增子级按钮
function addChild(val) {
  clearForm()
  form.parentId = val.deptId
  form.createBy = store.getUser.userName
  title.value = '添加部门'
  open.value = true
}

//修改按钮
function update(val) {
  clearForm()
  form.updateBy = store.getUser.userName
  form.deptId = val.deptId
  form.parentId = val.parentId
  form.deptName = val.deptName
  form.orderNum = val.orderNum
  form.leader = val.leader
  form.phone = val.phone
  form.email = val.email
  form.status = val.status
  radio.value = val.status
  title.value = '修改部门'
  open.value = true
}

//删除按钮
function del(val) {
  ElMessageBox.confirm('您确定要删除<' + val.deptName + '>部门吗？', '警告', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delDeptData({deptId: val.deptId}).then(result => {
      if (result.data.code === 200) {
        ElNotification({
          message: result.data.msg,
          type: 'success'
        })
      }
      getData()
    })
  })
}

//搜索表单
const search = reactive({
  deptName: null,
  status: null,
})

//赋值表格数据
const tableData = reactive({
  data: []
})
getData()

function getData() {
  loading.value = true;
  getDeptData(search).then(result => {
    tableData.data = result.data.data
    loading.value = false
  })
}

//表单校验
const rules = reactive<FormRules>({
  parentId: [
    {required: true, message: "上级部门不能为空", trigger: "blur"}
  ],
  deptName: [
    {required: true, message: "部门名称不能为空", trigger: "blur"}
  ],
  orderNum: [
    {required: true, message: "显示排序不能为空", trigger: "blur"}
  ],
  email: [
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"]
    }
  ],
  phone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ]
})

const btnLoading = ref(false)

//提交新增、修改表单
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      btnLoading.value = true
      form.status = radio.value
      saveDeptData(form).then(result => {
        if (result.data.code === 200) {
          ElNotification({
            message: result.data.msg,
            type: 'success'
          })
          open.value = false
        }
        getData()
        btnLoading.value = false
      })
    }
  })
}

//重置表单
function resetForm() {
  search.status = null
  search.deptName = null
  getData()
}
</script>

<style scoped>

</style>
